package com.treeliked.udpdemo.cs;

import com.treeliked.udpdemo.model.Message;
import com.treeliked.udpdemo.page.p2.Server;
import com.treeliked.udpdemo.service.UdpService;
import com.treeliked.udpdemo.service.impl.ServerServiceImpl;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * udp server
 *
 * @author lss
 * @date 2019-01-03, Thu
 */
public class UdpServer extends BaseClientServer {

    /**
     * 服务端端口号
     */
    public static final int DEFAULT_SERVER_PORT = 8880;

    /**
     * 服务端端口号
     */
    private int serverPort;
    /**
     * 服务端socket
     */
    private DatagramSocket ds;

    /**
     * 已发送消息数量
     */
    private long messageSendNum = 0;

    /**
     * 已接受消息数量
     */
    private long messageReceiveNum = 0;


    private UdpService service;

    public UdpServer(int serverPort, Server server) throws SocketException {
        this.serverPort = serverPort;
        this.ds = new DatagramSocket(serverPort);
        service = new ServerServiceImpl(ds, server);
    }

    public void setServerPort(int serverPort) {
        this.serverPort = serverPort;
    }

    public long getMessageSendNum() {
        return messageSendNum;
    }

    public void setMessageSendNum(long messageSendNum) {
        this.messageSendNum = messageSendNum;
    }

    public long getMessageReceiveNum() {
        return messageReceiveNum;
    }

    public void setMessageReceiveNum(long messageReceiveNum) {
        this.messageReceiveNum = messageReceiveNum;
    }


    public void startReceive() throws IOException {
        service.startReceive(this);
    }

    public void stopReceive() throws IOException {
        service.stopReceive();
    }

    public void sendMessage(Message msg) throws IOException {
        service.send(msg);
    }

    public void sendACKOk(int clientPort, String msgId) throws IOException {
        Message msg = new Message(serverPort, clientPort);
        msg.setMsgType(Message.MESSAGE_TYPE_ACK);
        msg.setAckResult(Message.ACK_RESULT_OK);
        msg.setContent(msgId);
        sendMessage(msg);
    }

    public int getServerPort() {
        return serverPort;
    }

    public void sendACKReSend(int clientPort, String msgId) throws IOException {
        Message msg = new Message(serverPort, clientPort);
        msg.setMsgType(Message.MESSAGE_TYPE_ACK);
        msg.setAckResult(Message.ACK_RESULT_RESEND);
        msg.setContent(msgId);
        sendMessage(msg);
    }
}


